package com.atguigu.cos.service.impl;

import com.atguigu.commonutils.R;
import com.atguigu.cos.service.CosService;
import com.atguigu.cos.utils.ConstantPropertiesUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.Key;
import java.util.Calendar;
import java.util.UUID;

/**
 * @author shkstart
 * @create 2022-09-17 20:43
 */
@Service
public class CosServiceImpl implements CosService {
    //    //密钥id
//    private final String SECRET_ID="AKIDaz82f16vVv5xZuylHWT9ZmhLipfEWYKo";
//    //密钥key
//    private final String SECRET_KEY="EDuKTLwGJ5aolRrzqPhiTxA7mAH7gZBW";
//    //储存库用户名
//    private final String BUCKET_NAME="edu-guli-2103-1313755920";
//    //地区
//    private final String REGION_ID="ap-guangzhou";

    //上传文件到cos
    @Override
    public String uploadFileAvatar(MultipartFile file) throws Exception {
        //密钥id
        String SECRET_ID = ConstantPropertiesUtils.SECRET_ID;
        //密钥key
        String SECRET_KEY = ConstantPropertiesUtils.SECRET_KEY;
        //存储库用户名
        String BUCKET_NAME = ConstantPropertiesUtils.BUCKET_NAME;
        //地区
        String REGION_ID = ConstantPropertiesUtils.REGION_ID;

        //1 初始化用户身份信息(secretId,secretKey)
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);

        //2 设置bucket的区域，COS地域的简称请参照...
        ClientConfig clientConfig = new ClientConfig(new Region(REGION_ID));

        //3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);

        //这里修改一下文件名字
        String oldFileName = file.getOriginalFilename();

        //对原始文件名进行判断
        String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
        if (!suffix.equalsIgnoreCase(".png") && !suffix.equalsIgnoreCase(".jpg") && !suffix.equalsIgnoreCase(".webp")
                && !suffix.equalsIgnoreCase(".svg") && !suffix.equalsIgnoreCase(".gif")) {
            throw new GuliException(20001, "上传的图片后缀名格式错误！");
        }

        //新名字
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String newFileName = uuid + suffix;

        //简单文件上传，最大支持5GB，适用于小文件上传
        //大文件上传请参照API文档高级API上传
        File localFile = null;
        String url = "";
        try {
            localFile = File.createTempFile("temp", null);
            file.transferTo(localFile);

            //把文件按照日期进行分类
            //获取当前日期
            //方法一：使用工具类
            //String datePath = new DateTime().toString("yyyy/MM/dd");
            //String KEY1 = "img/" + datePath + "/" + newFileName;

            //方法二：使用Calendar函数
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int date = calendar.get(Calendar.DATE);

            //指定要上传COS上的路径
            String KEY = "img/" + year + "/" + month + "/" + date + "/" + newFileName;
//            String KEY = newFileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, KEY, localFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

            //putObjectResult会返回文件的etag
            URL objectUrl = cosClient.getObjectUrl(BUCKET_NAME, KEY);//线上地址URL

            //把上传之后文件路径返回
            //需要把上传到腾讯云路径手动拼接出来
            url = objectUrl.toString();
            System.out.println(url);

            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return "" + e.getMessage();
        } finally {
            //关闭客户端（关闭后台线程）
            cosClient.shutdown();
        }
    }
}
